{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Adaptive Rounding (AdaRound)\n",
    "This notebook contains a working example of AIMET adaptive rounding (AdaRound).\n",
    "\n",
    "AIMET quantization features typically use the \"nearest rounding\" technique for achieving quantization.\n",
    "When using the nearest rounding technique, the weight value is quantized to the nearest integer value.\n",
    "\n",
    "AdaRound optimizes a loss function using unlabeled training data to decide whether to quantize a specific weight to the closer integer value or the farther one.\n",
    "Using AdaRound, quantized accuracy is closer to the FP32 model than with nearest rounding.\n",
    "\n",
    "## Overall flow\n",
    "\n",
    "The example follows these high-level steps:\n",
    "\n",
    "1. Instantiate the example evaluation and training pipeline\n",
    "2. Load the FP32 model and evaluate the model to find the baseline FP32 accuracy\n",
    "3. Create a quantization simulation model (with fake quantization ops) and evaluate the quantized simuation model\n",
    "4. Apply AdaRound and evaluate the simulation model to get a post-finetuned quantized accuracy score\n",
    "\n",
    "\n",
    "<div class=\"alert alert-info\">\n",
    "\n",
    "Note\n",
    "\n",
    "This notebook does not show state-of-the-art results. For example, it uses a relatively quantization-friendly model (Resnet18). Also, some optimization parameters like number of fine-tuning epochs are chosen to improve execution speed in the notebook.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## Dataset\n",
    "\n",
    "This example does image classification on the ImageNet dataset. If you already have a version of the data set, use that. Otherwise download the data set, for example from https://image-net.org/challenges/LSVRC/2012/index .\n",
    "\n",
    "<div class=\"alert alert-info\">\n",
    "\n",
    "Note\n",
    "\n",
    "To speed up the execution of this notebook, you can use a reduced subset of the ImageNet dataset. For example: The entire ILSVRC2012 dataset has 1000 classes, 1000 training samples per class and 50 validation samples per class. However, for the purpose of running this notebook, you can reduce the dataset to, say, two samples per class.\n",
    "\n",
    "</div>\n",
    "\n",
    "Edit the cell below to specify the directory where the downloaded ImageNet dataset is saved."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "DATASET_DIR = '/path/to/dataset/'         # Replace this path with a real directory"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## 1. Instantiate the example training and validation pipeline\n",
    "\n",
    "**Use the following training and validation loop for the image classification task.**\n",
    "\n",
    "Things to note:\n",
    "\n",
    "- AIMET does not put limitations on how the training and validation pipeline is written. AIMET modifies the user's model to create a QuantizationSim model, which is still a PyTorch model. The QuantizationSim model can be used in place of the original model when doing inference or training.\n",
    "- AIMET doesn not put limitations on the interface of the `evaluate()` or `train()` methods. You should be able to use your existing evaluate and train routines as-is.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "from Examples.common import image_net_config\n",
    "from Examples.tensorflow.utils.keras.image_net_dataset import ImageNetDataset\n",
    "from Examples.tensorflow.utils.keras.image_net_evaluator import ImageNetEvaluator\n",
    "\n",
    "\n",
    "class ImageNetDataPipeline:\n",
    "    \"\"\"\n",
    "    Provides APIs for model evaluation and finetuning using ImageNet Dataset.\n",
    "    \"\"\"\n",
    "\n",
    "    @staticmethod\n",
    "    def get_val_dataset() -> tf.data.Dataset:\n",
    "        \"\"\"\n",
    "        Instantiates a validation dataloader for ImageNet dataset and returns it\n",
    "        :return: A tensorflow dataset\n",
    "        \"\"\"\n",
    "        data_loader = ImageNetDataset(DATASET_DIR,\n",
    "                                      image_size=image_net_config.dataset['image_size'],\n",
    "                                      batch_size=image_net_config.evaluation['batch_size'])\n",
    "\n",
    "        return data_loader\n",
    "\n",
    "    @staticmethod\n",
    "    def evaluate(model, iterations=None) -> float:\n",
    "        \"\"\"\n",
    "        Given a Keras model, evaluates its Top-1 accuracy on the validation dataset\n",
    "        :param model: The Keras model to be evaluated.\n",
    "        :param iterations: The number of iterations to run. If None, all the data will be used\n",
    "        :return: The accuracy for the sample with the maximum accuracy.\n",
    "        \"\"\"\n",
    "        evaluator = ImageNetEvaluator(DATASET_DIR,\n",
    "                                      image_size=image_net_config.dataset[\"image_size\"],\n",
    "                                      batch_size=image_net_config.evaluation[\"batch_size\"])\n",
    "\n",
    "        return evaluator.evaluate(model=model, iterations=iterations)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "---\n",
    "## 2. Load the model and evaluate to get a baseline FP32 accuracy score"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**2.1 Load a pretrained resnet18 model from torchvision.** \n",
    "\n",
    "You can load any pretrained PyTorch model instead."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from tensorflow.keras.applications.resnet50 import ResNet50\n",
    "\n",
    "model = ResNet50(include_top=True,\n",
    "                 weights=\"imagenet\",\n",
    "                 input_tensor=None,\n",
    "                 input_shape=None,\n",
    "                 pooling=None,\n",
    "                 classes=1000)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "**2.2 Compute the floating point 32-bit (FP32) accuracy of this model using the evaluate() routine.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "ImageNetDataPipeline.evaluate(model=model, iterations=10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## 3. Create a quantization simulation model and determine quantized accuracy\n",
    "\n",
    "### Fold Batch Normalization layers\n",
    "\n",
    "Before calculating the simulated quantized accuracy using QuantizationSimModel, fold the BatchNormalization (BN) layers into adjacent Convolutional layers. The BN layers that cannot be folded are left as they are.\n",
    "\n",
    "BN folding improves inference performance on quantized runtimes but can degrade accuracy on these platforms. This step simulates this on-target drop in accuracy. \n",
    "\n",
    "The following code calls AIMET to fold the BN layers of a given model. </br>\n",
    "**NOTE: During folding, a new model is returned. Please use the returned model for the rest of the pipeline.**\n",
    "\n",
    "**3.1 Use the following code to call AIMET to fold the BN layers on the model.**\n",
    "\n",
    "<div class=\"alert alert-info\">\n",
    "\n",
    "Note\n",
    "\n",
    "Folding returns a new model. Use the returned model for the rest of the pipeline.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from aimet_tensorflow.keras.batch_norm_fold import fold_all_batch_norms\n",
    "\n",
    "_, model = fold_all_batch_norms(model)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Create the Quantization Sim Model\n",
    "\n",
    "**3.2 Use AIMET to create a QuantizationSimModel.**\n",
    "\n",
    " In this step, AIMET inserts fake quantization ops in the model graph and configures them.\n",
    "\n",
    "Key parameters:\n",
    "\n",
    "- Setting **default_output_bw** to 8 performs all activation quantizations in the model using integer 8-bit precision\n",
    "- Setting **default_param_bw** to 8 performs all parameter quantizations in the model using integer 8-bit precision\n",
    "\n",
    "See [QuantizationSimModel in the AIMET API documentation](https://quic.github.io/aimet-pages/AimetDocs/api_docs/torch_quantsim.html#aimet_torch.quantsim.QuantizationSimModel.compute_encodings) for a full explanation of the parameters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from aimet_tensorflow.keras.quantsim import QuantizationSimModel\n",
    "from aimet_common.defs import QuantScheme\n",
    "\n",
    "sim = QuantizationSimModel(model=model,\n",
    "                           quant_scheme=QuantScheme.post_training_tf,\n",
    "                           rounding_mode=\"nearest\",\n",
    "                           default_output_bw=8,\n",
    "                           default_param_bw=8)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "AIMET has added quantizer nodes to the model graph, but before the sim model can be used for inference or training, scale and offset quantization parameters must be calculated for each quantizer node by passing unlabeled data samples through the model to collect range statistics. This process is sometimes referred to as calibration. AIMET refers to it as \"computing encodings\".\n",
    "\n",
    "**3.3 Create a routine to pass unlabeled data samples through the model.** \n",
    "\n",
    "The following code is one way to write a routine that passes unlabeled samples through the model to compute encodings. It uses the existing train or validation data loader to extract samples and pass them to the model. Since there is no need to compute loss metrics, it ignores the model output.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensorflow.keras.utils import Progbar\n",
    "from tensorflow.keras.applications.resnet import preprocess_input\n",
    "\n",
    "def pass_calibration_data(sim_model, samples):\n",
    "    tf_dataset = ImageNetDataPipeline.get_val_dataset()\n",
    "    dataset = tf_dataset.dataset\n",
    "    batch_size = tf_dataset.batch_size\n",
    "\n",
    "    progbar = Progbar(samples)\n",
    "\n",
    "    batch_cntr = 0\n",
    "    for inputs, _ in dataset:\n",
    "        sim_model(preprocess_input(inputs))\n",
    "\n",
    "        batch_cntr += 1\n",
    "        progbar_stat_update = \\\n",
    "            batch_cntr * batch_size if (batch_cntr * batch_size) < samples else samples\n",
    "        progbar.update(progbar_stat_update)\n",
    "        if (batch_cntr * batch_size) > samples:\n",
    "            break\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A few notes regarding the data samples:\n",
    "\n",
    "- A very small percentage of the data samples are needed. For example, the training dataset for ImageNet has 1M samples; 500 or 1000 suffice to compute encodings.\n",
    "- The samples should be reasonably well distributed. While it's not necessary to cover all classes, avoid extreme scenarios like using only dark or only light samples. That is, using only pictures captured at night, say, could skew the results.\n",
    "\n",
    "---\n",
    "\n",
    "**3.4 Call AIMET to pass data through the model and compute the quantization encodings.** \n",
    "\n",
    "Encodings here refer to scale and offset quantization parameters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "sim.compute_encodings(forward_pass_callback=pass_calibration_data,\n",
    "                      forward_pass_callback_args=1000)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "**3.5 Determine the simulated quantized accuracy of the equalized model. Create a simulation model like before and evaluate it to calculate accuracy.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "ImageNetDataPipeline.evaluate(model=sim.model, iterations=10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "## 4. Apply Adaround\n",
    "\n",
    "**4.1 Use the code below to apply Adaround to the original model.**\n",
    "\n",
    "Some key parameters:\n",
    "\n",
    "- **data_set:**  AdaRound needs a dataset to learn the rounding vectors. Either a training or validation dataloader can be passed in.\n",
    "- **num_batches:** is the number of batches used while calculating the quantization encodings. A typical value for Adaround is 2000 samples. To speed up the execution this example uses a batch size of one.\n",
    "- **default_num_iterations:** is the number of iterations to apply to each layer. Default value is 10000, and we strongly recommend using at least this number. This example uses 32 to speed up execution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import os\n",
    "from tensorflow.keras.applications.resnet import preprocess_input\n",
    "from tensorflow.keras.preprocessing import image_dataset_from_directory\n",
    "from aimet_tensorflow.keras.adaround_weight import Adaround, AdaroundParameters\n",
    "\n",
    "ada_round_data = image_dataset_from_directory(directory=DATASET_DIR,\n",
    "                                              labels=\"inferred\",\n",
    "                                              label_mode=\"categorical\",\n",
    "                                              batch_size=image_net_config.evaluation[\"batch_size\"],\n",
    "                                              shuffle=False,\n",
    "                                              image_size=(image_net_config.dataset[\"image_width\"],\n",
    "                                                          image_net_config.dataset[\"image_height\"]))\n",
    "ada_round_data = ada_round_data.map(lambda x, y: preprocess_input(x))\n",
    "\n",
    "params = AdaroundParameters(data_set=ada_round_data, num_batches=1, default_num_iterations=32)\n",
    "\n",
    "os.makedirs(\"./output/\", exist_ok=True)\n",
    "ada_model = Adaround.apply_adaround(model, params, path=\"output\", filename_prefix=\"adaround\",\n",
    "                                    default_param_bw=8, default_quant_scheme=QuantScheme.post_training_tf)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "**4.2 Quantize the Adarounded model.** \n",
    "\n",
    "<div class=\"alert alert-info\">\n",
    "\n",
    "Note\n",
    "\n",
    "Two important points about the following code:\n",
    "\n",
    "</div>\n",
    "\n",
    "- **Parameter Biwidth Precision**: The QuantizationSimModel must be created with the same parameter bitwidth precision that was used in `apply_adaround()`.\n",
    "    \n",
    "- **Freezing the parameter encodings**:\n",
    "After creating the QuantizationSimModel, you must call `set_and_freeze_param_encodings()` before calling `compute_encodings()`.\n",
    "During AdaRound, the parameters are rounded based on these initial internally created encodings.\n",
    "To maintain accuracy, it is important to freeze these encodings so that the call to `compute_encodings()` does not alter the parameter encodings negate the AdaRounded accuracy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "sim = QuantizationSimModel(model=ada_model,\n",
    "                           quant_scheme=QuantScheme.post_training_tf,\n",
    "                           rounding_mode=\"nearest\",\n",
    "                           default_output_bw=8,\n",
    "                           default_param_bw=8)\n",
    "\n",
    "sim.set_and_freeze_param_encodings(encoding_path=os.path.join(\"output\", \"adaround.encodings\"))\n",
    "\n",
    "sim.compute_encodings(forward_pass_callback=pass_calibration_data,\n",
    "                      forward_pass_callback_args=1000)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "**4.3 Compute the accuracy of the Adarounded model.** \n",
    "\n",
    "Evaluate the simulation model as before to determine simulated quantized accuracy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "ImageNetDataPipeline.evaluate(model=sim.model, iterations=10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "There might be little gain in accuracy after this limited application of Adaround. Experiment with the hyper-parameters to get better results.\n",
    "\n",
    "## Next steps\n",
    "\n",
    "**Export the model and encodings.**\n",
    "\n",
    "- Export the model with the updated weights but without the fake quant ops. \n",
    "- Export the encodings (scale and offset quantization parameters). AIMET QuantizationSimModel provides an export API for this purpose.\n",
    "\n",
    "The following code performs these exports."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "sim.export(path=\"./output\", filename_prefix=\"resnet50_after_adaround\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## For more information\n",
    "\n",
    "See the [AIMET API docs](https://quic.github.io/aimet-pages/AimetDocs/api_docs/index.html) for details about the AIMET APIs and optional parameters.\n",
    "\n",
    "See the [other example notebooks](https://github.com/quic/aimet/tree/develop/Examples/torch/quantization) to learn how to use other AIMET post-training quantization techniques."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.8.0 64-bit",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "3.8.0"
  },
  "vscode": {
   "interpreter": {
    "hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
